package com.ydlclass;

import com.ydlclass.discovery.Registry;
import com.ydlclass.discovery.impl.NacosRegistry;
import com.ydlclass.discovery.impl.ZookeeperRegistry;
import com.ydlclass.exceptions.DiscoveryException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Author duWenJian
 * @Date 2024/2/10 17:48
 * @Version 1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RegistryConfig {
    /**
     * 定义连接的 url zookeeper://127.0.0.1:2181  redis://127.0.0.1:3306
     */
    private String connectString;

    /**
     * toLowerCase 转化成小写
     * trim 去除前后空格
     * 获取用户输入的注册中心
     * @return
     */
    public Registry getRegistry() {
        String RegistryType = getRegistryType(this.connectString , true).toLowerCase().trim();
        if (Constant.REGISTRY_TYPE_ZOOKEEPER.equals(RegistryType)) {
            String ConnectString = getRegistryType(this.connectString, false);
            return new ZookeeperRegistry(ConnectString , Constant.TIME_OUT);
        }
        if (Constant.REGISTRY_TYPE_NACOS.equals(RegistryType)) {
            String ConnectString = getRegistryType(this.connectString, false);
            return new NacosRegistry(ConnectString , Constant.TIME_OUT);
        }

        throw new DiscoveryException("未发现合适的注册中心");
    }

    private String getRegistryType(String connectString , boolean ifType){
        String[] typeAndHost = connectString.split("://");
        if (typeAndHost.length != Constant.TYPE_HOST_LENGTH){
            throw new RuntimeException("给定的注册中心的连接url不合法");
        }
        if (typeAndHost[0] == null && typeAndHost[0].equals("")) {
            throw new RuntimeException("给定的注册中心的Type类型不正确");
        }
        if (typeAndHost[1] == null && typeAndHost[1].equals("")) {
            throw new RuntimeException("给定的注册中心的Host类型不正确");
        }
        if (ifType){
            return typeAndHost[0];
        } else {
            return typeAndHost[1];
        }
    }
}
